package rd.hardcore.engine.datas 
{
	//import air.net.SecureSocketMonitor;
	import com.carlcalderon.arthropod.Debug;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.utils.ByteArray;
	import nochump.util.zip.ZipEntry;
	import nochump.util.zip.ZipFile;
	import rd.hardcore.datas.Track;
	import rd.hardcore.engine.save.SaveManager;
	import rd.hardcore.events.SaveManagerEvent;
	/**
	 * ...
	 * @author Fazermokeur
	 */
	public class DatasManager
	{
		
		private static var _vGrid:Vector.<GridDatasManager>;
		private static var trackAutoDone:Track;
		private static var sm:SaveManager;
		private static var hardcoreLoader:URLStream;
		
		public function DatasManager() 
		{
			_vGrid = new Vector.<GridDatasManager>();
		}
		
		public function init(tracksXML:XML, padsXML:XML):void
		{
			var pads:XML = padsXML;
			var node:XML;
			var g:GridDatasManager;
			for each( node in pads.children() ) {
				g = new GridDatasManager(node.@id);
				g.init(node, tracksXML);
				_vGrid.push(g);
			}
			
		}
		
		/**
		 * Ajout d'une grille de pads complete
		 * @TODO	ajout d'un noeud padmanager et des 26 pads noeuds track corespondant
		 */
		public function addGrid():void
		{
			
		}
		
		/**
		 * Ajout de contenu d'un pad en remplissant au premier pad non remplit
		 */
		static public function addPadDefault(url:String):void
		{
			var id:Number = firstEmptyPad();
			if (!isNaN(id)) {
				trackAutoDone = getTrackById(id);
				sm = new SaveManager(trackAutoDone.keyId);
				var f:File = new File(url);
				hardcoreLoader = new URLStream();
				hardcoreLoader.addEventListener(Event.COMPLETE, hardcoreFileLoaded);
				hardcoreLoader.load( new URLRequest( f.url));
			}else {
				/*	C'est la merde	*/
			}
		}
		
		/**
		 * Supprime un pad 
		 * @param	keyId
		 */
		static public function deletePadById(keyId:int):void
		{
			var t:Track = getTrackById(keyId);
			t.thumb = "medias/thumbs/empty.jpg";
			t.file	= "medias/thumbs/empty.mp3";
			SaveManager.updateTracksXML();
			t.updateSoRefresh();
		}
		
		/**
		 * Génération du XML pour écriture dans pads.xml
		 * @return	contenu du noeud data
		 */
		public static function getPadsXML():XML
		{
			var node:XML = <pads/>;
			var len:int = _vGrid.length;
			for (var i:int = 0; i < len; i++) 
			{
				node.appendChild(_vGrid[i].getPadManagerNode());
			}
			
			return node;
		}
		
		/**
		 * Génération du XML pour écriture dans tracks.xml
		 * @return	contenu du noeud data
		 */
		public static function getTracksXML():XML
		{
			var node:XML = <tracks/>;
			var len:int = _vGrid.length;
			for (var i:int = 0; i < len; i++) 
			{
				node.appendChild(_vGrid[i].getXMLTracksList());
			}
			return node;
		}
		
		/**
		 * Récupération d'un track par keyId
		 * @param	keyId
		 * @return	Track
		 */
		static public function getTrackById(keyId:int):Track
		{
			var len:int = _vGrid.length;
			var t:Track;
			for (var i:int = 0; i < len; i++) 
			{
				t = _vGrid[i].getTrackById(keyId);
				if (t != null)	return t;
			}
			
			return null;
		}
		
		public static function firstEmptyPad():Number
		{
			var len:int = _vGrid.length;
			var t:Number;
			for (var i:int = 0; i < len; i++) 
			{
				t = _vGrid[i].firstEmptyPads();
				if (!isNaN(t)) return t;
			}
			
			return NaN;
		}
		
		static public function checkUniqueFile(file:String, thumb:String):Boolean
		{
			var len:int = _vGrid.length;
			for (var i:int = 0; i < len; i++) {
				if (_vGrid[i].checkUniqueFile(file, thumb)) {
					Debug.log("RETURN TRUE "+i);
					return true;
				}
			}
			
			return false;
		}
		
		
		/* Hardcore Extension Handler */
		static private function hardcoreFileLoaded( evt : Event ) : void
		{	
			var jpgLoaded:Boolean = false;
			var mp3Loaded:Boolean = false;
			var jpgName:String;
			var mp3Name:String;
			
			hardcoreLoader.removeEventListener(Event.COMPLETE, hardcoreFileLoaded);
			
			var zipFile:ZipFile = new ZipFile(hardcoreLoader);
			
			for (var i:int = 0; i < zipFile.entries.length; i++)
			{
				var entry:ZipEntry = zipFile.entries[i];
				// extract the entry's data from the zip
				var data:ByteArray = zipFile.getInput(entry);
				
				
				/* JPG */
				if ( entry.name.search("jpg") > 0 )
				{
					var picture : File =  new File( SaveManager.URL_PATH_THUMB + "/" + entry.name );
					
					var fs : FileStream = new FileStream();
					fs.open( picture, FileMode.WRITE);
					fs.writeBytes( data );
					fs.close();
					Debug.log("entry.name = " + entry.name);
					trackAutoDone.thumb = entry.name;
					
					sm.copyImgFile = picture;
					
					jpgLoaded = true;
				}
				
				/* MP3 */
				if ( entry.name.search("mp3") > 0 )
				{
					var sound : File =  new File( SaveManager.URL_PATH_MP3 + "/" + entry.name );
					Debug.log("entry.name = " + entry.name);
					var mfs: FileStream = new FileStream();
					mfs.open( sound, FileMode.WRITE);
					mfs.writeBytes( data );
					mfs.close();
					
					trackAutoDone.file = entry.name;
					
					sm.copySongFile = sound;
					
					
					mp3Loaded = true;
				}
				
			}
			
			//if (checkUniqueFile(SaveManager.URL_PATH_MP3 + "/" + mp3Name, SaveManager.URL_PATH_THUMB + "/" + jpgName)) return false;
				
				if (jpgLoaded && mp3Loaded) {
					sm.addEventListener(SaveManagerEvent.SAVE_PROCESS_SUCCEED, handleSaveProcessComplete);
					sm.proceedDaSave(trackAutoDone, true);
				}
			
		}
		
		static private function handleSaveProcessComplete(e:SaveManagerEvent):void 
		{
			//trackAutoDone.updateSoRefresh();
		}
	}

}